from flask_restx import Namespace, fields, Resource

from web.restapi.cpe_convert import message

api = Namespace(
    "dbinfo",
    description="Endpoints displaying information about the cve search database",
    path="/",
)

database_inner = api.model(
    "DBInner",
    {
        "last_update": fields.DateTime(
            description="Date time of last update", example="2019-09-30T18:53:48"
        ),
        "size": fields.Integer(
            description="Amount of documents in collection", example="570"
        ),
    },
)

database_wild = fields.Wildcard(
    fields.Nested(database_inner),
    description="Database collection mapping id",
    skip_none=True,
)

database_entry = api.model("documents", {"*": database_wild})


@api.route("/dbinfo")
@api.response(400, "Error processing request", model=message)
@api.response(500, "Server error", model=message)
class DBInfo(Resource):
    @api.marshal_with(database_entry)
    def get(self):
        """
        Get Database info

        Returns the stats of the database. When the user authenticates, more information is returned.

        This information includes:
        <ul>
          <li> Amount of whitelist and blacklist records </li>
          <li> Some server settings like the database name </li>
          <li> Some database information like disk usage </li>
        </ul>
        Unauthenticated queries return only collection information.
        """
        from lib.DatabaseLayer import getDBStats

        return getDBStats()
